package com.rpc.demo.common.config;

import com.rpc.demo.common.constant.ZookeeperConst;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/6
 * @Description:
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */

public class RegisterCenter {

    private static Logger logger = LoggerFactory.getLogger(RegisterCenter.class);
    private ZooKeeper zk;

    /**
     * @author: zhaojie
     * @date: 2022/4/6
     * @description: 连接zookeeper服务，并且创建相应的dubbo节点
     * @method: RegisterCenter
     * @param null
     * @class:  RegisterCenter
     * @return:
     */
    public RegisterCenter() {
        try {
            CountDownLatch connectedSignal = new CountDownLatch(1);
            zk = new ZooKeeper(ZookeeperConst.host, 5000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                        connectedSignal.countDown();
                    }
                }
            });
            // 监听器异步操作
            connectedSignal.await();

            // 创建dubbo的注册节点的根节点（持久化节点）
            if (zk.exists(ZookeeperConst.rootNode, false) == null) {
                zk.create(ZookeeperConst.rootNode, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

        } catch (Exception e) {
            logger.error("connect zookeeper server error.", e);
        }
    }

    /**
     * @author: zhaojie
     * @date: 2022/4/6
     * @description: 将服务和服务提供者注册到注册中心
     * @method: register
     * @param null
     * @class:  RegisterCenter
     * @return:
     */
    public void register(String serviceName, String serviceProviderAddress) {
        try {
            String servicePath = ZookeeperConst.rootNode + "/" + serviceName;
            if (zk.exists(servicePath, false) == null) {
                zk.create(servicePath, "".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            //创建服务提供者节点
            String serviceProviderPath = servicePath + "/" + serviceProviderAddress;
            if (zk.exists(serviceProviderPath, false) == null) {
                zk.create(serviceProviderPath, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            }
            logger.info("服务注册成功, 服务路径: " + serviceProviderPath);
        } catch (Exception e) {
            logger.error("注册中心-注册服务报错", e);
        }
    }

}
